<script setup>
import { Modal } from 'ant-design-vue'
import { ArrowLeftOutlined, EyeOutlined, ImportOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, UpOutlined } from '@ant-design/icons-vue'
import { getDict, getLogDetail, getLogList, rePull } from '~@/api/checkBill/index'

import { getMerchantList } from '~@/api/card/index'

defineOptions({
  name: 'PullBill',
})
const userStore = useUserStore()
const { hasPermission } = userStore
const message = useMessage()
const bankOptions = shallowRef([])
const bankLoading = shallowRef(false)
const payOptions = shallowRef([])

const columns = shallowRef([
  {
    title: '银行名称',
    dataIndex: 'appName',
    width: 250,
  },
  {
    title: '账单日期',
    align: 'left',
    dataIndex: 'accountDate',
    width: 150,
  },

  {
    title: '支付方式',
    dataIndex: 'channelName',
    align: 'center',
    width: 150,
  },

  {
    title: '对账状态',
    dataIndex: 'status',
    align: 'center',
    width: 180,
    customRender: ({ text }) => {
      if (text === 0) {
        return '未执行'
      }
      else if (text === 1) {
        return '成功'
      }
      else {
        return '失败'
      }
    },

  },
  {
    title: 'HIS账单拉取状态',
    dataIndex: 'platformAccountStatus',
    align: 'center',
    width: 180,
    customRender: ({ text }) => {
      if (text === 0) {
        return '未执行'
      }
      else if (text === 1) {
        return '成功'
      }
      else {
        return '失败'
      }
    },
  },
  {
    title: '第三方账单拉取状态',
    dataIndex: 'channelAccountStatus',
    align: 'center',
    width: 180,
    customRender: ({ text }) => {
      if (text === 0) {
        return '未执行'
      }
      else if (text === 1) {
        return '成功'
      }
      else {
        return '失败'
      }
    },
  },

  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 250,

  },
])
const billOptions = shallowRef([
  { configKey: '', configValue: '全部' },
  { configKey: 'CARD_EXPENSE', configValue: '消费明细' },
  { configKey: 'CARD_RECHARGE', configValue: '充值明细' },
])
const activeKey = ref(['1'])
const customStyle
  = 'background: #f7f7f7;border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden'
const detailInfo = shallowRef({
  appName: void 0,
  platRequestNo: void 0,
  accountNo: void 0,
  appId: void 0,
  cardNo: void 0,
  tradeType: void 0,
  tradeDate: void 0,
  channel: void 0,
  phone: void 0,
  userName: void 0,
  requestCompleteTime: void 0,
  requestStartTime: void 0,
  channelName: void 0,
  defrayFee: void 0,
  status: void 0,
  origPlatRequestNo: void 0,
  defrayNo: void 0,

})
const loading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  billType: void 0,
  updatedAt: void 0,
  logDate: void 0,
})
const staticInfo = reactive({
  cardCount: void 0,
  refundAmount: void 0,
  defrayAmount: void 0,
  balance: void 0,
  withdrawAmount: void 0,
  rechargeAmount: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  init()
  getPayType()
})
// 查询支付方式
async function getPayType() {
  try {
    const { data } = await getDict('payChannel')
    payOptions.value = data
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 查询卡信息
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const createBeginTime = formModel.logDate?.[0]?.format('YYYY-MM-DD')
    const createEndTime = formModel.logDate?.[1]?.format('YYYY-MM-DD')
    const params = {
      dateStart: formModel.logDate?.[0]?.format('YYYY-MM-DD'),
      dateEnd: formModel.logDate?.[1]?.format('YYYY-MM-DD'),
      channel: formModel.channel,
      appId: formModel.appId,
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },
    }
    const { data } = await getLogList(params)

    dataSource.value = data.data ?? []
    // dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 日志详情
async function viewLog(record) {
  if (loading.value)
    return
  loading.value = true
  try {
    const dateStart = formModel.logDate?.[0]?.format('YYYY-MM-DD')
    const dateEnd = formModel.logDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await getLogDetail({
      accountDate: record.accountDate,
      appId: record.appId,
      channel: record.channel,
    })
    activeKey.value = 1
    open.value = true
    detailInfo.value = data
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 执行对账
async function handleRepull(record) {
  if (loading.value)
    return
  loading.value = true
  try {
    const params = {
      accountDate: record.accountDate,
      appId: record.appId,
      channel: record.channel,
      insurance: record.insurance,
    }
    const { data } = await rePull(params)
    message.warning(data.message)
    loading.value = false
  }
  catch (e) {
    console.log(e)
    loading.value = false
  }
  finally {
    loading.value = false
  }
}

// 防抖优化接口请求
async function fetchOptions(value) {
  if (!value.trim()) {
    bankOptions.value = []
    return
  }
  bankLoading.value = true
  const { data } = await getMerchantList(value)
  bankOptions.value = data
  bankLoading.value = false
};
async function onSearch() {
  pagination.current = 1
  await init()
}
function handleReturn() {
  open.value = false
}
// 重置查询参数
async function onReset() {
  formModel.logDate = void 0
  formModel.appId = void 0
  formModel.channel = void 0
  await init()
}
function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
function handleCheckAllChange(e) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}
const expand = ref(false)
</script>

<template>
  <page-container>
    <div>
      <a-card mb-4>
        <a-form :model="formModel" :label-col="{ span: 7 }">
          <a-row :gutter="[15, 0]">
            <a-col :span="8">
              <a-form-item name="logDate" label="查询日期">
                <a-range-picker v-model:value="formModel.logDate" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="appId" label="医院名称">
                <a-select
                  v-model:value="formModel.appId"
                  show-search
                  placeholder="请输入关键字搜索"
                  allow-clear
                  :filter-option="false"
                  :not-found-content="bankLoading ? '加载中...' : '暂无数据'"
                  @search="fetchOptions"
                >
                  <a-select-option v-for="item in bankOptions" :key="item.appId" :value="item.appId">
                    {{ item.appName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="支付方式">
                <a-select v-model:value="formModel.channel" placeholder="请选择" allow-clear>
                  <a-select-option v-for="item in payOptions" :key="item.configKey" :value="item.configKey">
                    {{ item.configValue }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24" style="text-align: right">
              <a-space>
                <a-button type="primary" @click="onSearch">
                  查询
                </a-button>
                <a-button @click="onReset">
                  重置
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </a-card>

      <a-card>
        <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'balance'">
              <span :style="{ color: record.balance < 0 ? 'red' : 'black' }">{{ Number(record.balance).toFixed(2) }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'billType'">
              {{ record.billType === 'CARD_EXPENSE' ? '消费明细' : '充值明细' }}
            </template>

            <template v-else-if="column.dataIndex === 'action'">
              <div class="flex items-center">
                <a-button type="link" style="padding: 4px 5px;" @click="viewLog(record)">
                  <EyeOutlined />日志详情
                </a-button>
                <span class="middle-line">|</span>
                <a-button type="link" style="padding: 4px 5px;" @click="handleRepull(record)">
                  <ImportOutlined />执行对账
                </a-button>
              </div>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
    <a-drawer width="600" placement="right" :closable="false" :open="open" @close="onClose">
      <div class="flex flex-wrap justify-between returnBack">
        <span class="card-title">日志详情</span>
        <a-button @click="handleReturn">
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回
        </a-button>
      </div>

      <a-divider />
      <a-collapse
        v-model:active-key="activeKey"
        :bordered="false"
        style="background: rgb(255, 255, 255)"
      >
        <a-collapse-panel key="1" header="HIS订单拉取" :style="customStyle">
          <!-- his订单拉取 -->
          <div class="ml-4">
            <a-timeline v-if="detailInfo.getPlatformAccount && detailInfo.getPlatformAccount.length > 0" class="mt-4">
              <a-timeline-item v-for="(item, index) in detailInfo && detailInfo.getPlatformAccount" :key="index" color="gray">
                <div class="his-title">
                  <span class="left-title">{{ item.actionMemo }}</span>
                </div>
                <div class="adjust mt-2">
                  <span class="left-title mr-5">{{ item.actionTime }}</span><span class="left-title mr-5">{{ item.appName }}</span><span class="left-title">{{ item.channelName }}</span>
                </div>
              </a-timeline-item>
            </a-timeline>
            <div v-else>
              <span class="color-gray">暂无数据</span>
            </div>
          </div>
        </a-collapse-panel>
        <a-collapse-panel key="2" header="第三方订单拉取" :style="customStyle">
          <!-- 第三方订单拉取 -->
          <div class="ml-4">
            <a-timeline v-if="detailInfo.getChannelAccountData && detailInfo.getChannelAccountData.length > 0" class="mt-4">
              <a-timeline-item v-for="(item, index) in detailInfo && detailInfo.getChannelAccountData" :key="index" color="gray">
                <div class="his-title">
                  <span class="left-title">{{ item.actionMemo }}</span>
                </div>
                <div class="adjust mt-2">
                  <span class="left-title mr-5">{{ item.actionTime }}</span><span class="left-title mr-5">{{ item.appName }}</span><span class="left-title">{{ item.channelName }}</span>
                </div>
              </a-timeline-item>
            </a-timeline>
            <div v-else>
              <span class="color-gray">暂无数据</span>
            </div>
          </div>
        </a-collapse-panel>
        <a-collapse-panel key="3" header="对账状态拉取" :style="customStyle">
          <!-- 对账状态拉取 -->
          <div class="ml-4">
            <a-timeline v-if="detailInfo.accountReconcileImpl && detailInfo.accountReconcileImpl.length > 0" class="mt-4">
              <a-timeline-item v-for="(item, index) in detailInfo && detailInfo.accountReconcileImpl" :key="index" color="gray">
                <div class="his-title">
                  <span class="left-title">{{ item.actionMemo }}</span>
                </div>
                <div class="adjust mt-2">
                  <span class="left-title mr-5">{{ item.actionTime }}</span><span class="left-title mr-5">{{ item.appName }}</span><span class="left-title">{{ item.channelName }}</span>
                </div>
              </a-timeline-item>
            </a-timeline>
            <div v-else>
              <span class="color-gray">暂无数据</span>
            </div>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </a-drawer>
  </page-container>
</template>

  <style lang="less" scoped>
    .returnBack{
      position: absolute;
      top: 0px;
      background: #fff;
      width: 90%;
      z-index: 111;
      padding: 20px 0;
    }
    .red{
      color:red;
      /* color:#ff4d4f; */
    }
    .adjust{
      color:#777;
    }
    .card-title{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex: auto;
      color: rgba(0, 0, 0, 0.88);
      font-weight: 600;
      font-size: 16px;
      line-height: 1.5;
    }
  @media screen and (max-width: 1200px) and (min-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      margin-left: -44px;
      .statItem {
        padding: 0 16px;
      }
    }
  }

  @media screen and (max-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      float: none;
      margin-right: 0;
      .statItem {
        padding: 0 16px;
        text-align: left;
        &::after {
          display: none;
        }
      }
    }
  }

  @media screen and (max-width: 768px) {
    .extraContent {
      margin-left: -16px;
    }
    .projectList {
      .projectGrid {
        width: 50%;
      }
    }
  }

  @media screen and (max-width: 576px) {
    .pageHeaderContent {
      display: block;
      .content {
        margin-left: 0;
      }
    }
    .extraContent {
      .statItem {
        float: none;
      }
    }
  }

  @media screen and (max-width: 480px) {
    .projectList {
      .projectGrid {
        width: 100%;
      }
    }
  }
  </style>
